package net.csdn.business.common.feign.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import feign.FeignException;
import feign.Response;
import feign.RetryableException;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.enums.ResultCodeEnum;
import net.csdn.business.common.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author likun
 * @date 2022/6/24 10:56
 */
@Slf4j
// @Configuration
public class AliFeignErrorDecoder extends ErrorDecoder.Default {
    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = super.decode(methodKey, response);
        log.error("AliFeignErrorDecoder method:{} ex:{}", methodKey, JSON.toJSONString(exception));

        // 如果是RetryableException，则返回继续重试
        if (exception instanceof RetryableException) {
            return exception;
        }

        if (exception instanceof FeignException) {
            int status = ((FeignException) exception).status();
            String content = ((FeignException) exception).responseBody().map(s -> StandardCharsets.UTF_8.decode(s).toString()).orElse("");
            String msg = ResultCodeEnum.THIRD_ERROR.getMsg();
            if (StringUtils.isNotBlank(content)) {
                try {
                    //此处优化，由于云校异常未返回error_message，eg:{"cause":"抱歉，系统开小差了，请稍后再试","errorCode":"SYSTEM_UNKNOWN_ERROR","message":"SSH Key格式错误","pushRuleExist":false,"status":false,"traceId":"ac10010216758429617941906d0021"}
                    JSONObject body = JSON.parseObject(content);
                    msg = StringUtils.isBlank(body.getString("message")) ? body.getString("cause"):body.getString("message");
                }catch (Exception e){

                }
            }
            status = status == 500 ? 400 : status;
            return new BusinessException(status, msg);
        } else {
            return exception;
        }
    }
}